<template>
  <div class="user-list-page">
    <!-- 页面标题和操作区域 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">用户管理</h1>
          <p class="page-subtitle">管理和组织系统用户</p>
        </div>
        <div class="action-section">
          <el-button type="primary" size="large" @click="openAddDialog" class="upload-btn">
            <el-icon :size="18"><DocumentAdd /></el-icon> &nbsp;
            新增用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="filter-section">
      <div class="filter-container">
        <el-input
          v-model="searchText"
          placeholder="搜索用户名/邮箱/电话"
          clearable
          class="search-input user-search-input"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          style="background-color: rgba(255,255,255,0.22);"
        >
          <template #prefix>
            <el-icon><i class="el-icon-search"></i></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        <el-button @click="resetSearch" class="reset-btn">重置</el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <el-card class="table-card">
        <el-table :data="users" v-loading="loading" border class="document-table">
          <el-table-column label="序号" width="60">
            <template #default="{ $index }">
              {{ (page - 1) * pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="phoneNumber" label="电话" />
          <el-table-column prop="roles" label="角色">
            <template #default="{ row }">
              <el-tag v-for="role in row.roles" :key="role" type="info" style="margin-right:4px;">{{ role || '无' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="90">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                {{ row.status === 'active' ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" @click="openEditDialog(row)" class="action-btn">编辑</el-button>
                <el-button size="small" type="danger" @click="confirmDelete(row)" class="action-btn">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="val => { pageSize = val; page = 1; updatePageData(); }"
            @current-change="val => { page = val; updatePageData(); }"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="showDialog" :title="dialogMode === 'add' ? '新增用户' : '编辑用户'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="form.roles" multiple placeholder="请选择角色">
            <el-option label="管理员" value="系统管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="确认删除" width="300px">
      <div>确定要删除该用户吗？</div>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/user'

const usersAll = ref([])
const users = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const searchText = ref('')

const showDialog = ref(false)
const dialogMode = ref('add') // 'add' or 'edit'
const form = reactive({
  id: '',
  userName: '',
  email: '',
  phoneNumber: '',
  roles: [],   //用户角色名rolename
  status: 'active'
})
const formRef = ref()
const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  roles: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const showDeleteDialog = ref(false)
const deleteUserId = ref(null)

const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await userApi.getUserList()
    usersAll.value = res.data || []
    // 批量获取所有用户的角色
    await Promise.all(usersAll.value.map(async (user) => {
      try {
        const roleRes = await userApi.getUserRoles(user.id)        
        // 兼容返回数组或对象
        user.roles = Array.isArray(roleRes.data) ? roleRes.data.map(r => r.roleName || r) : []
      } catch {
        user.roles = []
      }
    }))
    total.value = usersAll.value.length
    // updatePageData()
    handleSearch()
  } catch (err) {
    ElMessage.error('获取用户列表失败：'+err)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  let filtered = usersAll.value
  const val = searchText.value.trim().toLowerCase()
  if (val) {
    filtered = usersAll.value.filter(u => {
      return (
        (u.userName && u.userName.toLowerCase().includes(val)) ||
        (u.email && u.email.toLowerCase().includes(val)) ||
        (u.phoneNumber && u.phoneNumber.toLowerCase().includes(val))
      )
    })
  }
  total.value = filtered.length
  page.value = 1
  updatePageData(filtered)
}

// 支持分页点击时不重置页码
const updatePageData = (data) => {
  const arr = data || (() => {
    const val = searchText.value.trim().toLowerCase()
    if (!val) return usersAll.value
    return usersAll.value.filter(u => {
      return (
        (u.userName && u.userName.toLowerCase().includes(val)) ||
        (u.email && u.email.toLowerCase().includes(val)) ||
        (u.phoneNumber && u.phoneNumber.toLowerCase().includes(val))
      )
    })
  })()
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  users.value = arr.slice(start, end)
}

const resetSearch = () => {
  searchText.value = ''
  handleSearch()
}


const openAddDialog = () => {
  dialogMode.value = 'add'
  Object.assign(form, { id: '', userName: '', email: '', phoneNumber: '', roles: [], status: 'active' })
  showDialog.value = true
}

const openEditDialog = (row) => {
  dialogMode.value = 'edit'
  Object.assign(form, row)
  showDialog.value = true
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (dialogMode.value === 'add') {
        const addForm = { ...form ,
          password: 'abc123456' // 默认密码
        }
        delete addForm.id // 新增时不需要id
        
        await userApi.addUser(addForm)
        ElMessage.success('新增成功')
      } else {
        await userApi.updateUserInfo(form.id, form)
        ElMessage.success('修改成功')
      }
      showDialog.value = false
      fetchUsers()
    } catch (err) {
      ElMessage.error(dialogMode.value === 'add' ? '新增失败' : '修改失败'+ err)
    }
  })
}

const confirmDelete = (row) => {
  deleteUserId.value = row.id
  showDeleteDialog.value = true
}

const handleDelete = async () => {
  try {
    await userApi.deleteUser(deleteUserId.value)
    ElMessage.success('删除成功')
    showDeleteDialog.value = false
    fetchUsers()
  } catch (err) {
    ElMessage.error('删除失败'+ err)
  }
}

function formatDateTime(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-search-input {
  background: rgba(255,255,255,0.22) !important;
  border-radius: 8px !important;
  min-width: unset;
  width: 160px;
  max-width: 100%;
}
/* 搜索栏样式，参考文档管理页面 */
.filter-section {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.2);
  backdrop-filter: blur(20px);
}
.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}
.search-input {
  flex: 1;
  min-width: 300px;
  
}
.reset-btn {
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.25);
  color: #ffffff;
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.reset-btn:hover {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.9) 0%, rgba(22, 33, 62, 0.9) 100%);
  color: #ffffff;
  border-color: rgba(0, 212, 255, 0.4);
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.1);
}
/* 引用文档管理页面的样式结构，保持风格一致 */
.user-list-page {
  padding: 32px;
}
.page-header {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9) 0%, rgba(147, 51, 234, 0.9) 100%);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.2);
  backdrop-filter: blur(20px);
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #fff;
  margin: 0;
}
.page-subtitle {
  font-size: 14px;
  color: #b3e5fc;
  margin: 0;
}
.action-section {
  display: flex;
  align-items: center;
}
.upload-btn {
  background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
  border: none !important;
  color: #fff !important;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 212, 255, 0.3) !important;
  padding: 8px 20px;
  font-size: 16px;
  transition: all 0.3s;
}
.upload-btn:hover {
  background: linear-gradient(135deg, #0099cc 0%, #0077a3 100%) !important;
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.4);
}
.table-section {
  margin-bottom: 24px;
}
.table-card {
  border-radius: 16px;
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%);
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.2);
  overflow: hidden;
  backdrop-filter: blur(20px);
}
.document-table {
  width: 100%;
}
.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-start;
  min-width: 0;
}
.action-btn {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  padding: 4px 8px;
  height: 28px;
  line-height: 1;
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
  white-space: nowrap;
  flex-shrink: 0;
}
.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 24px 0;
  background: rgba(0, 212, 255, 0.05);
  border-top: 1px solid rgba(0, 212, 255, 0.2);
}
/* Element Plus 组件样式覆盖 */
:deep(.el-table) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%) !important;
  color: #ffffff !important;
}
:deep(.el-table__body-wrapper),
:deep(.el-table__header-wrapper),
:deep(.el-table__fixed-body-wrapper),
:deep(.el-table__fixed-header-wrapper) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%) !important;
}
:deep(.el-table th) {
  background: rgba(0, 212, 255, 0.15) !important;
  color: #ffffff !important;
  border-bottom: 1px solid rgba(0, 212, 255, 0.4) !important;
  font-weight: 600 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5) !important;
}
:deep(.el-table td) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.8) 0%, rgba(22, 33, 62, 0.8) 100%) !important;
  color: #ffffff !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.15) !important;
  font-weight: 500 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
:deep(.el-table tr:hover > td) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.9) 0%, rgba(22, 33, 62, 0.9) 100%) !important;
  border-color: rgba(0, 212, 255, 0.4) !important;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.1) !important;
}
:deep(.el-table--border) {
  border: 1px solid rgba(0, 212, 255, 0.3) !important;
}
:deep(.el-table--border th) {
  border-right: 1px solid rgba(0, 212, 255, 0.3) !important;
}
:deep(.el-table--border td) {
  border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
}
:deep(.el-card) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
:deep(.el-button) {
  background: rgba(0, 212, 255, 0.25) !important;
  border: 1px solid rgba(0, 212, 255, 0.4) !important;
  color: #ffffff !important;
  backdrop-filter: blur(10px);
  font-weight: 500 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
:deep(.el-button:hover) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.9) 0%, rgba(22, 33, 62, 0.9) 100%) !important;
  border-color: rgba(0, 212, 255, 0.5) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 212, 255, 0.2) !important;
}
:deep(.el-button--primary) {
  background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
  border: none !important;
  box-shadow: 0 4px 12px rgba(0, 212, 255, 0.3) !important;
}
:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #0099cc 0%, #0077a3 100%) !important;
  box-shadow: 0 6px 16px rgba(0, 212, 255, 0.4) !important;
}
:deep(.el-tag) {
  background: rgba(0, 212, 255, 0.25) !important;
  border: 1px solid rgba(0, 212, 255, 0.4) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
:deep(.el-pagination) {
  background: transparent !important;
  color: #ffffff !important;
  font-weight: 500 !important;
}
:deep(.el-pager li) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.8) 0%, rgba(22, 33, 62, 0.8) 100%) !important;
  border: 1px solid rgba(255, 255, 255, 0.25) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
:deep(.el-pager li:hover) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.9) 0%, rgba(22, 33, 62, 0.9) 100%) !important;
  border-color: rgba(0, 212, 255, 0.4) !important;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.1) !important;
}
:deep(.el-pager li.is-active) {
  background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
  border-color: rgba(0, 212, 255, 0.6) !important;
}
:deep(.btn-prev),
:deep(.btn-next) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.8) 0%, rgba(22, 33, 62, 0.8) 100%) !important;
  border: 1px solid rgba(255, 255, 255, 0.25) !important;
  color: #ffffff !important;
  font-weight: 600 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
:deep(.btn-prev:hover),
:deep(.btn-next:hover) {
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.9) 0%, rgba(22, 33, 62, 0.9) 100%) !important;
  border-color: rgba(0, 212, 255, 0.4) !important;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.1) !important;
}
</style>